import streamlit as st
import cv2
import numpy as np
from authentication import Authentication
from haar_eye_detector import HaarEyeDetector
from alert_system import AlertSystem


class EyeDetectionUI:
    def __init__(self):
        self.auth = Authentication()
        self.eye_detector = HaarEyeDetector()
        self.alert_system = AlertSystem()
        self.cap = None

    def login_section(self):

        st.sidebar.title("用户登录")
        username = st.sidebar.text_input("用户名")
        password = st.sidebar.text_input("密码", type="password")

        if st.sidebar.button("登录"):
            if self.auth.login_user(username, password):
                st.session_state.logged_in = True
                st.session_state.username = username
                st.sidebar.success("登录成功!")
            else:
                st.sidebar.error("用户名或密码错误")

        if st.sidebar.button("注册新用户"):
            st.session_state.show_register = True

    def register_section(self):

        st.sidebar.title("用户注册")
        new_username = st.sidebar.text_input("新用户名")
        new_password = st.sidebar.text_input("新密码", type="password")
        confirm_password = st.sidebar.text_input("确认密码", type="password")
        email = st.sidebar.text_input("邮箱(可选)")

        if st.sidebar.button("注册"):
            if new_password != confirm_password:
                st.sidebar.error("密码不匹配")
            else:
                success, message = self.auth.register_user(new_username, new_password, email)
                if success:
                    st.sidebar.success(message)
                    st.session_state.show_register = False
                else:
                    st.sidebar.error(message)

        if st.sidebar.button("返回登录"):
            st.session_state.show_register = False

    def main_app(self):

        st.title("闭眼检测系统")
        st.write(f"欢迎, {st.session_state.username}!")


        st.info("""
        该系统使用Haar级联分类器检测眼睛状态。当检测到闭眼超过10秒时，会发出警报。
        请确保摄像头清晰可见您的面部，并保持良好光照条件。
        """)


        col1, col2 = st.columns(2)
        with col1:
            if st.button("开始检测", key="start"):
                st.session_state.start_detection = True
                self.eye_detector.reset()

        with col2:
            if st.button("停止检测", key="stop"):
                st.session_state.start_detection = False
                if self.cap:
                    self.cap.release()
                self.alert_system.stop_alert()


        if st.button("测试警报声音"):
            self.alert_system.play_alert_async()

        if st.session_state.get('start_detection', False):
            self.run_detection()

    def run_detection(self):
        """运行眼睛检测"""
        self.cap = cv2.VideoCapture(0)
        stframe = st.empty()
        alert_placeholder = st.empty()

        while st.session_state.get('start_detection', False):
            ret, frame = self.cap.read()
            if not ret:
                st.error("无法访问摄像头")
                break


            processed_frame, eyes_closed = self.eye_detector.detect_eyes(frame)
            processed_frame_rgb = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)

            # 显示处理后的帧
            stframe.image(processed_frame_rgb, use_container_width=True)

            if eyes_closed:
                alert_placeholder.warning(" 检测到闭眼超过10秒! 正在播放警报...")
                self.alert_system.play_alert_async()
            else:
                alert_placeholder.empty()

        if self.cap:
            self.cap.release()

    def run(self):
        if 'logged_in' not in st.session_state:
            st.session_state.logged_in = False
        if 'show_register' not in st.session_state:
            st.session_state.show_register = False
        if 'start_detection' not in st.session_state:
            st.session_state.start_detection = False

        if not st.session_state.logged_in:
            if st.session_state.show_register:
                self.register_section()
            else:
                self.login_section()
        else:
            self.main_app()